//编辑，详情动态表格
<template>
  <el-dialog
    v-el-drag-dialog="{minWidth: 750, updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :append-to-body="true"
    :width="setDialogWidth('90%')"
    :visible="visible"
    :title="rowData.isBizOtdrResult ? $t('TEST_CHANNEL') : $t('CHANNEL')"
    class="segment-list-box"
    @open="open"
    @close="close"
  >
    <!-- 业务基本信息显示 -->
    <biz-info v-if="!rowData.isBizOtdrResult" :form-data="rowData" />
    <div class="font-weight-bold pl-20">{{ $t('INTERMEDIATE_NODE') }}</div>
    <el-divider class="m-0 mt-10 mb-10" />
    <biz-graphical
      ref="bizGraphical"
      class="mb-20"
      :biz-channel-list="segmentList"
      :cable-data="cableData"
    />
    <!-- 通道信息 -->
    <el-table
      v-if="tableHead.length"
      id="channelTable"
      ref="segmentTable"
      border
      :data="segmentList"
      style="width: 100%"
      :max-height="360"
      size="mini"
      class="biz-table mb-20"
      :cell-class-name="cellClass"
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column
        type="index"
        :label="$t('SEQUENCE')"
        fixed="left"
        :width="resetSize(60)"
        align="center"
        :resizable="false"
      />
      <el-table-column
        v-if="!rowData.isBizOtdrResult"
        fixed="left"
        :label="$t('SERVICE_STATUS')"
        align="center"
        width="100"
        prop="bizStatus"
        show-overflow-tooltip
        :resizable="false"
      >
        <template v-slot="scope">
          {{ dictMap.BIZ_STATUS[scope.row.bizStatus] }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="!rowData.isBizOtdrResult"
        fixed="left"
        :label="$t('LOCKED')"
        align="center"
        width="100"
        show-overflow-tooltip
        :resizable="false"
      >
        <template slot="header">
          <span>{{ $t('LOCKED') }}</span>
          <el-popover width="200" trigger="hover">
            <div class="text-color" v-html="$t('LOCKED_TIPS')" />
            <i
              slot="reference"
              class="iconfont icon-AFSwenhao text-color ml-5 font-weight-normal"
            />
          </el-popover>
        </template>
        <template slot-scope="scope">
          <i
            class="lock-icon"
            :class="scope.row.lockStatus === 'LOCKED' ? 'el-icon-lock' : 'el-icon-unlock'"
            @click="changeLocked(scope.row)"
          />
          <span class="hidden">{{
            scope.row.lockStatus === 'LOCKED' ? $t('LOCK') : $t('UN_LOCKED')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableHead"
        :key="index"
        :label="item.cellName"
        align="center"
        show-overflow-tooltip
        :render-header="tableRenderHeader"
        min-width="110"
        :resizable="false"
      >
        <template
          v-if="index === 0 || index === tableHead.length - 1 || item.type === 'fiber'"
          v-slot="scope"
        >
          <div v-if="item.type === 'fiber'">
            {{
              scope.row[`segmentList${item.index}`]
                ? scope.row[`segmentList${item.index}`].fiber.fiberName
                : '--'
            }}
          </div>
          <div v-else>
            {{
              !scope.row[`segmentList${item.index}`]
                ? '--'
                : item.index === 0
                  ? scope.row[`segmentList${item.index}`].startPort.bizName
                  : scope.row[`segmentList${item.index}`].endPort.bizName
            }}
          </div>
        </template>
        <!-- 不能用v-else 会报错 -->
        <template v-if="index !== 0 && index !== tableHead.length - 1 && item.type === 'node'">
          <el-table-column
            :label="$t('A_END_NODE_PORT')"
            align="center"
            :prop="`segmentList${item.index}.endPort.bizName`"
            min-width="110"
            show-overflow-tooltip
            :resizable="false"
          >
            <template v-slot="scope">
              {{
                scope.row[`segmentList${item.index}`]
                  ? scope.row[`segmentList${item.index}`].endPort.bizName
                  : '--'
              }}
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('Z_END_NODE_PORT')"
            align="center"
            :prop="`segmentList${item.index + 1}.startPort.bizName`"
            min-width="110"
            show-overflow-tooltip
            :resizable="false"
          >
            <template v-slot="scope">
              {{
                scope.row[`segmentList${item.index + 1}`]
                  ? scope.row[`segmentList${item.index + 1}`].startPort.bizName
                  : '--'
              }}
            </template>
          </el-table-column>
        </template>
      </el-table-column>
      <el-table-column
        v-if="rowData.isBizOtdrResult"
        :label="$t('OTDR_TEST_RESULT')"
        min-width="80"
        :resizable="false"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showTestResult(scope.$index)">{{
            $t('DETAIL')
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:footer>
      <el-button type="primary" @click="$debounce(exportChannel)">{{ $t('EXPORT') }}</el-button>
      <el-button @click="close">{{ $t('CLOSE') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import bizChannelApi from '@/api/oen/BizChannelApi'
  import { tableRenderHeader } from '@/utils/common'
  import BizGraphical from '@/components/BizGraphical'
  import cableFiberApi from '@/api/oen/CableFiberApi'
  import BizInfo from './components/BizInfo'
  import { tableToExcel } from '@/utils/jsonToExcel'
  import OperateLogApi from '@/api/system/OperateLogApi.js'

  export default {
    name: 'SegmentDetail',
    components: { BizInfo, BizGraphical },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['functionName'],
    data() {
      return {
        segmentList: [],
        tableHead: [],
        cableData: {}
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'getUserId', 'getUser']),
      permission() {
        return this.$store.getters.getAuthData('biz:manager')
      }
    },
    methods: {
      tableRenderHeader(h, data) {
        return tableRenderHeader(h, data)
      },
      open() {
        this.tableHead = []
        this.segmentList = []
        console.log('rowData', this.rowData)

        if (this.rowData.isBizOtdrResult) {
          this.formatData(this.rowData.bizChannelList)
        } else {
          bizChannelApi.getDetailByBizId({ bizId: this.rowData.bizId }).then(res => {
            this.formatData(res)
          })
        }
      },
      // 数据组装 组装表头信息和列表数据信息
      formatData(bizChannelList) {
        console.log('bizChannelList', bizChannelList)
        const nodeList = []
        bizChannelList.forEach((j, pIndex) => {
          j.segmentList.forEach((i, index) => {
            if (pIndex === 0) {
              // 第一条数据用来拼接表头
              index === 0 &&
                nodeList.push({
                  cellName: i.startNode.nodeName,
                  type: 'node',
                  index: index
                })
              // 有光缆添加光缆
              if (i.fiber) {
                nodeList.push({
                  cellName: i.fiber.fiberName,
                  fiberId: i.fiber.fiberId,
                  type: 'fiber',
                  index: index
                })
              }
              // 默认添加endNode
              nodeList.push({
                cellName: i.endNode.nodeName,
                type: 'node',
                index: index
              })
            }
            i.startPort.bizName = this.$utils.handleServiceI18n(i.startPort.bizName)
            i.endPort.bizName = this.$utils.handleServiceI18n(i.endPort.bizName)
            j['segmentList' + index] = i
          })
          if (pIndex === 0) {
            this.tableHead = nodeList
            this.getCableInfo()
          }
        })
        this.segmentList = bizChannelList
      },
      getCableInfo() {
        const fiberList = this.tableHead.filter(i => i.type === 'fiber').map(i => i.fiberId)
        cableFiberApi.getByFiberIdList(fiberList).then(res => {
          if (res) {
            this.cableData = res
            this.tableHead.forEach(i => {
              if (i.type === 'fiber') {
                i.cellName = res[i.fiberId] ? res[i.fiberId].cableName : ''
              }
            })
            this.$nextTick(() => {
              this.$refs.bizGraphical && this.$refs.bizGraphical.formatData()
            })
            this.showGraphical = true
          }
        })
      },
      cellClass({ row, column }) {
        const statusColor = [
          {
            color: 'normal',
            status: ['RESTORE', 'NORMAL']
          },
          {
            color: 'fault',
            status: ['FAULT']
          },
          {
            color: 'doing',
            status: [
              'OPENING',
              'RESTORING',
              'RETURNING',
              'OPEN_FAIL',
              'RESTORE_FAIL',
              'REDUCTION_FAIL',
              'RETURN_FAIL'
            ]
          }
        ]
        if (column.property === 'bizStatus') {
          const colorData =
            statusColor.find(i => i.status.includes(row.bizStatus)) || statusColor[0]
          return 'color-' + colorData.color
        }
      },
      // 修改锁定状态
      changeLocked(data) {
        const changeStatus = (data.lockStatus =
          data.lockStatus === 'UNLOCKED' ? 'LOCKED' : 'UNLOCKED')
        bizChannelApi
          .updateStatus({
            channelId: data.channelId,
            lockStatus: changeStatus
          })
          .then(res => {
            if (res) {
              this.$message.success(this.$t('MODIFY_SUCCESS'))
              data.lockStatus = changeStatus
              this.$emit('reload')
            }
          })
      },
      exportChannel() {
        const infoData = [
          [
            this.$t('SERVICE_NAME') + '：' + this.rowData.bizName,
            null,
            null,
            null,
            this.$t('SERVICE_STATUS') + '：' + this.dictMap.BIZ_STATUS[this.rowData.bizStatus],
            null,
            null,
            null,
            this.$t('SERVICE_CODE') + '：' + this.rowData.resourceCode
          ]
        ]
        tableToExcel(
          'channelTable',
          this.$t('BIZ_CHANNEL_EXPORT_NAME', { bizName: this.rowData.bizName }),
          infoData
        )
        this.addLog() // OTDR测试记录 导出通道列表
      },
      showTestResult(index) {
        console.log(index, this.rowData)
        const processId = this.rowData.processId
        const taskId = this.rowData.taskIdList[index]
        this.$emit('showTestResult', { processId, taskId, index })
      },
      addLog() {
        // item必须是菜单的名字，否则影响根据操作项筛选日志的功能
        let item = 'MENU_BUSINESS_MANAGER'
        if (this.functionName === 'homeTopo') {
          item = 'HOME_TOPOLOGY_MAP' // 系统首页-拓扑图
        }
        if (this.functionName === 'homeGis') {
          item = 'HOME_GIS_MAP' // 系统首页-GIS展示
        }
        if (this.functionName === 'manager') {
          item = 'MENU_BUSINESS_MANAGER' // 业务管理
        }
        const obj = {
          api: '/',
          item: item, // 业务管理
          object: this.rowData.bizName,
          terminal: 'EXPORT_SERVICE_CHANNEL', // 导出业务通道
          operateResult: true,
          realName: this.getUser.realName,
          content: JSON.stringify({
            bizName: this.rowData.bizName,
            currentUserId: this.getUserId,
            i18nKey: 'EXPORT_SERVICE_CHANNEL_LOG'
          })
        }
        // 记录登录日志
        OperateLogApi.addLog(obj)
      },
      close(data) {
        this.$emit('close', data)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .lock-icon {
    font-size: 16px;
    cursor: pointer;

    &.el-icon-lock {
      color: #409eff;
    }
  }
</style>
